<?php

namespace Hilaoyu\LaravelExtend\Services\Files;


use Hilaoyu\LaravelExtend\Services\AccessControl\Traits\ModelWithAccessControlFilterTrait;
use Hilaoyu\Utils\UtilFile;
use Hilaoyu\Utils\UtilSupport;
use Hilaoyu\LaravelExtend\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

abstract class FilesModelAbstract extends Model
{

    public $_chche_expire_time = null;

    use ModelWithAccessControlFilterTrait;

    public function accessGetAccessIdentifier():string
    {
        return 'files';
    }

    protected $url_absolute = false;

    protected $table = 'files';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'disk',
        'path',
        'type',
        'ext',
        'size',
        'mime',
        'hash_md5',
        'secret',
        'extra',
        'owner_id',
        'owner_model',
        'upload_task',
        'upload_is_completed',
        'is_permanent',
        'app_id',
    ];


    protected $hidden = [
        'disk',
        'path',
        'secret',
        'owner_id',
        'owner_model',
        //'is_permanent',
        'real_disk',
        'is_encoded',
        'app_id',
    ];

    protected $casts = [
        'extra' => 'json',
        'upload_task' => 'json',
    ];
    protected $appends = [
        'real_disk',
        'url',
        'is_encoded',
        'size_show'
    ];

    public function getValidationRules()
    {
        $rules = [
            'disk' => 'required|string|max:254',
            'path' => 'required|string|max:254',
        ];

        return $rules;
    }

    public function setUrlAbsolute($bool = true)
    {
        $this->url_absolute = (bool)$bool;
    }


    public function getUrlAttribute()
    {
        return (new FileService('', '', $this))->url($this->url_absolute);
    }

    public function getIsEncodedAttribute()
    {
        return (bool)$this->getAttribute('secret');
    }

    public function getSizeShowAttribute()
    {
        return UtilFile::sizeFormat($this->getAttribute('size'));
    }

    public function getRealDiskAttribute()
    {
        if ('1' == $this->getAttribute('is_permanent')) {
            return data_get($this->attributes, 'disk', '');

        }
        return FileService::tempDisk();
    }

    static public function loadCacheModel($id)
    {
        $id = trim($id);
        if (!$id) {
            return null;
        }
        $attributes = Cache::get('laravel-extend-files-model-cache-' . $id);
        if ($attributes) {

            $model = new static();
            $model->_chche_expire_time = data_get($attributes, '_chche_expire_time');
            unset($attributes['_chche_expire_time']);

            $model->forceFill($attributes);
            $model->syncOriginal();
            //$model->exists = true;
            return $model;
        }
        return null;
    }

    public function saveToCache($ttl = null)
    {

        if ($this->fireModelEvent('saving') === false) {
            return false;
        }
        if (!$id = $this->getKey()) {
            return false;
        }
        /*if(is_null($ttl)){
            $ttl = Carbon::now()->addSeconds(config('file_service.temp_file_hold_time',60 * 60 *24));
        }*/
        $hidden = $this->getHidden();
        $appends = $this->appends;
        $this->setHidden([]);
        $this->setAppends([]);
        $attributes = $this->attributesToArray();
        $this->setHidden($hidden);
        $this->setAppends($appends);
        $attributes['_chche_expire_time'] = (string)$ttl;
        $this->_chche_expire_time = $attributes['_chche_expire_time'];

        $status = Cache::put('laravel-extend-files-model-cache-' . $id, $attributes, $ttl);

        if ($status) {
            $this->syncOriginal();
            //$this->exists = true;
        }
        return $status;
    }

    public function deleteCache()
    {


        if (!$id = $this->getKey()) {
            return false;
        }

        return Cache::forget('laravel-extend-files-model-cache-' . $id);
    }

    public function cacheLifeTime()
    {

        return $this->_chche_expire_time;
    }


}
